package com.cyh;

import java.util.concurrent.atomic.AtomicStampedReference;

public class StampCas {
    static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0); //初始版本号0
    public static void main(String[] args) {
        //获取值
        String prev = ref.getReference();
        //获取版本号
        int stamp = ref.getStamp();
        new Thread(() -> {
            int stamp2 = ref.getStamp();
            if(ref.compareAndSet(ref.getReference(), "B", stamp2, stamp2 + 1)) { //版本号+1  true
                System.out.println("修改成功");
            }
        }, "t1").start();
        new Thread(() -> {
            int stamp2 = ref.getStamp();
            if(ref.compareAndSet(ref.getReference(), "A", stamp2, stamp2 + 1)) { //版本号+1 true
                System.out.println("修改成功2");
            }
        }, "t2").start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(ref.compareAndSet(ref.getReference(), "C", stamp, stamp + 1)) { //版本号+1  false 因为版本号改动了
            System.out.println("修改成功3");
        }
    }
}
